package api;

import Utils.DBUtil;
import Utils.SessionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.ApplcationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.ResultData;
import model.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/deldish")
public class DelDishServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer did=Integer.valueOf(req.getParameter("did"));
        int state=-1;
        String msg="未知错误";
        List<Dish> data=new ArrayList<>();
        //验证登录信息
        UserInfo userInfo= SessionUtil.getSessionUserInfo(req);
        if(userInfo!=null){//已经登录
            if(did!=null && did>0){
                //参数有效，执行删除操作
                Connection connection = DBUtil.getConnection();
                String sql=" update dish set isdelete =? where did=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,1);
                statement.setInt(2,did);
                int result = statement.executeUpdate();
                if(result>0){
                    state=200;
                    msg="操作成功";
                }
                String sql1 = "select * from dish where isdelete=?";
                PreparedStatement statement1 = connection.prepareStatement(sql1);
                statement1.setInt(1,0);
                ResultSet resultSet = statement1.executeQuery();
                while (resultSet.next()) {
                    Dish dish = new Dish();
                    dish.setDid(resultSet.getInt("did"));
                    dish.setName(resultSet.getString("name"));
                    dish.setPrice(resultSet.getBigDecimal("price"));
                    dish.setIsdown(resultSet.getInt("isdown"));
                    dish.setCreatetime(resultSet.getString("createtime"));
                    dish.setSelect(false);
                    data.add(dish);
                }
            }else{
                msg="参数无效";
            }
        }
        resp.setContentType(ApplcationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,data,msg)));
    }
}
